/**
 * 
 */
package com.mths.client.page;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.MultiSelectionModel;
import com.mths.client.component.Button;
import com.mths.client.component.ComboBox;
import com.mths.client.component.GridData;
import com.mths.client.component.TabPanel;
import com.mths.client.constant.PageConstant;
import com.mths.client.controller.DocumentController;
import com.mths.client.controller.DocumentControllerAsync;
import com.mths.client.dto.DocMetaSaveDTO;
import com.mths.client.dto.DocMetaSearchDTO;
import com.mths.client.dto.MetaDataDTO;
import com.mths.client.util.AsyncCall;
import com.mths.client.util.ListItem;
import com.mths.client.util.PageUtil;

/**
 * @author ibesli
 * 
 */
public class DocumentMatchCreate extends AbstractPage implements IPage {

	private static DocumentCreateMatchUiBinder	uiBinder	= GWT.create(DocumentCreateMatchUiBinder.class);

	interface DocumentCreateMatchUiBinder extends UiBinder<Widget, DocumentMatchCreate> {
	}

	private final DocumentControllerAsync	documentAsync	= GWT.create(DocumentController.class);

	@UiField
	TabPanel								documentTabPnl;

	@UiField
	ComboBox								docClassCmb, docTypeCmb;

	@UiField
	Button									saveBtn;

	@UiField
	GridData<MetaDataDTO>					releatedMetaTbl, allMetaTbl;

	public DocumentMatchCreate() {
		initWidget(uiBinder.createAndBindUi(this));
		initEventHandler();
		initGridData();
		loadComponentData();
	}

	private void initGridData() {
		createDocReleatedMetaTable();
		createAllMetaTable();
	}

	private void createAllMetaTable() {

		TextColumn<MetaDataDTO> fieldNameClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldName();
			}
		};
		fieldNameClm.setSortable(true);

		TextColumn<MetaDataDTO> fieldTypeClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldType();
			}
		};
		TextColumn<MetaDataDTO> fieldOrderClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldOrder().toString();
			}
		};

		ButtonCell moveUpBtn = new ButtonCell();
		Column<MetaDataDTO, String> moveUpColumn = new Column<MetaDataDTO, String>(moveUpBtn) {
			@Override
			public String getValue(MetaDataDTO object) {
				return "Yukarı taşı";
			}
		};
		moveUpColumn.setFieldUpdater(new FieldUpdater<MetaDataDTO, String>() {
			public void update(int index, MetaDataDTO metaData, String value) {
				moveMeta2Releated(metaData, index);
			}
		});

		// docTypeMeta celltable
		final MultiSelectionModel<MetaDataDTO> allMetaSelection = new MultiSelectionModel<MetaDataDTO>();
		allMetaTbl.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		allMetaTbl.addColumn(fieldNameClm, "Meta Data Adı");
		allMetaTbl.addColumn(fieldTypeClm, "Meta Tipi ");
		allMetaTbl.addColumn(fieldOrderClm, "Dizilim Sırası");
		allMetaTbl.addColumn(moveUpColumn, "");
		allMetaTbl.setRowCount(10);
		allMetaTbl.setSelectionModel(allMetaSelection);

		allMetaTbl.clear();

	}

	private void createDocReleatedMetaTable() {
		TextColumn<MetaDataDTO> fieldNameClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldName();
			}
		};
		fieldNameClm.setSortable(true);

		TextColumn<MetaDataDTO> fieldTypeClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldType();
			}
		};
		TextColumn<MetaDataDTO> fieldOrderClm = new TextColumn<MetaDataDTO>() {

			@Override
			public String getValue(MetaDataDTO object) {
				return object.getFieldOrder().toString();
			}
		};

		ButtonCell moveDownBtn = new ButtonCell();

		Column<MetaDataDTO, String> moveDownColumn = new Column<MetaDataDTO, String>(moveDownBtn) {
			@Override
			public String getValue(MetaDataDTO object) {
				return "Aşağı taşı";
			}
		};
		moveDownColumn.setFieldUpdater(new FieldUpdater<MetaDataDTO, String>() {
			public void update(int index, MetaDataDTO object, String value) {
				moveMeta2All(object, index);
			}
		});

		// docTypeMeta celltable
		final MultiSelectionModel<MetaDataDTO> docMetaSelection = new MultiSelectionModel<MetaDataDTO>();
		releatedMetaTbl.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		releatedMetaTbl.addColumn(fieldNameClm, "Meta Data Adı");
		releatedMetaTbl.addColumn(fieldTypeClm, "Meta Tipi ");
		releatedMetaTbl.addColumn(fieldOrderClm, "Dizilim Sırası");
		releatedMetaTbl.addColumn(moveDownColumn, "");
		releatedMetaTbl.setRowCount(10);
		releatedMetaTbl.setSelectionModel(docMetaSelection);
		releatedMetaTbl.setTitle("Aşağıdaki tablodan kayıtları seçip bu tabloya aktararak dosya ile ilişkilendirebilirsiniz.");
		releatedMetaTbl.clear();

	}

	private void moveMeta2Releated(MetaDataDTO metaData, int index) {
		allMetaTbl.remove(metaData);
		// allMetaProvider.refresh();
		releatedMetaTbl.putData(metaData);
		// releatedMetaProvider.refresh();
	}

	private void moveMeta2All(MetaDataDTO metaData, int index) {
		releatedMetaTbl.remove(metaData);
		allMetaTbl.putData(metaData);

	}

	private void initEventHandler() {
		documentTabPnl.selectTab(4);
		documentTabPnl.addSelectionHandler(new SelectionHandler<Integer>() {

			@Override
			public void onSelection(SelectionEvent<Integer> event) {
				if (event.getSelectedItem() == 0) {
					PageUtil.navigationManager.controlOpenPageByFUrl(PageConstant.DOCUMENT_META_CREATE);
				} else if (event.getSelectedItem() == 1) {
					PageUtil.navigationManager.controlOpenPageByFUrl(PageConstant.DOCUMENT_META_PARAM_CREATE);
				} else if (event.getSelectedItem() == 2) {
					PageUtil.navigationManager.controlOpenPageByFUrl(PageConstant.DOCUMENT_CLASS_CREATE);
				} else if (event.getSelectedItem() == 3) {
					PageUtil.navigationManager.controlOpenPageByFUrl(PageConstant.DOCUMENT_TYPE_CREATE);
				} else if (event.getSelectedItem() == 4) {
					// loadDocumentType()
				}
			}
		});

		docClassCmb.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				docTypeCmb.clear();
				loadDocTypeCombo();
			}
		});

		docTypeCmb.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				findDocRelatedMetaData();
			}
		});

		saveBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				saveDocReleatedMetas();
			}
		});
	}

	private void saveDocReleatedMetas() {
		List<MetaDataDTO> metaDataList = new ArrayList<MetaDataDTO>();
		for (MetaDataDTO metaData : releatedMetaTbl.getList()) {
			metaDataList.add(metaData);
		}

		DocMetaSaveDTO dto = new DocMetaSaveDTO();
		dto.setDocReleatedMetaList(metaDataList);
		dto.setDocTypeOid(docTypeCmb.getFieldValue());

		documentAsync.saveDocMetaDataList(dto, new AsyncCall<Void>() {

			@Override
			public void successCall(Void result) {
				findDocRelatedMetaData();
			}

		});
	}

	private void loadComponentData() {
		loadDocClassCombo();
	}

	private void loadDocClassCombo() {
		documentAsync.loadDocClassCombo("", new AsyncCall<List<ListItem>>() {

			@Override
			public void successCall(List<ListItem> result) {
				docClassCmb.addItemList(result);
			}

		});
	}

	private void loadDocTypeCombo() {
		documentAsync.loadDocTypeCombo(docClassCmb.getFieldValue(), new AsyncCall<List<ListItem>>() {

			@Override
			public void successCall(List<ListItem> result) {
				docTypeCmb.addItemList(result);
			}

		});
	}

	private void findDocRelatedMetaData() {
		if (docTypeCmb.getFieldValue() == null || docTypeCmb.getFieldValue().isEmpty())
			return;

		documentAsync.loadDocMetaDataList(docTypeCmb.getFieldValue(), new AsyncCall<DocMetaSearchDTO>() {
			@Override
			public void successCall(DocMetaSearchDTO result) {
				// Push the data into the widget.
				if (result != null && result.getDocReleatedMetaList() != null) {
					releatedMetaTbl.clear();
					releatedMetaTbl.putDataList(result.getDocReleatedMetaList());
				}

				if (result != null && result.getAllMetaDataList() != null) {
					allMetaTbl.clear();
					allMetaTbl.putDataList(result.getAllMetaDataList());
				}

			}
		});
	}

	@Override
	public String pageName() {
		return messages.DocumentMatchCreate_pageName();
	}
}
